package com.dl7.mvp.music.ui;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dl7.mvp.XApp;
import com.dl7.mvp.music.bean.MusicInfo;
import com.dl7.mvp.music.service.MusicService;
import com.dl7.mvp.mvp.R;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class QuickControlsFragment extends Fragment implements XApp.ServiceBindListener{
    private ProgressBar mProgress;
    private ImageView mPlayPause;
    private TextView mTitle;
    private ImageView mAlbumArt;
    private ImageView mNext;
    private ImageView mPrev;
    private View mRootView;

    public static QuickControlsFragment newInstance() {
        return new QuickControlsFragment();
    }

    private Timer mTimer = new Timer();
    MusicService.PlayerBinder mBinder;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.music_controller, container, false);
        mRootView = rootView;
        rootView.setVisibility(View.GONE);
        mPlayPause = rootView.findViewById(R.id.control);
        mProgress = rootView.findViewById(R.id.song_progress_normal);
        mTitle = rootView.findViewById(R.id.music_title);
        mAlbumArt = rootView.findViewById(R.id.music_img);
        mNext = rootView.findViewById(R.id.play_next);
        mPrev = rootView.findViewById(R.id.play_prev);

        mPlayPause.setOnClickListener(v -> {
            togglePlay();
        });

        mNext.setOnClickListener(view -> {
            Handler handler = new Handler();
            handler.post(() -> mBinder.playNext());

        });

        mPrev.setOnClickListener(view -> {
            Handler handler = new Handler();
            handler.post(() -> mBinder.playPrev());

        });

       // mTimer.schedule(mTimerTask, 0, 1000);

        XApp.bindMusicService(this);

        return rootView;
    }

    @Override
    public void onDestroy() {
        mTimer.cancel();
        super.onDestroy();
    }

    /*******************************************************
     * 通过定时器和Handler来更新进度条
     ******************************************************/
    TimerTask mTimerTask = new TimerTask() {
        @Override
        public void run() {
            if (mBinder == null)
                return;
            if (mBinder.isPlaying()) {
                handleProgress.sendEmptyMessage(0);
            }
        }
    };

    Handler handleProgress = new Handler() {
        public void handleMessage(Message msg) {
            if (mBinder == null) {
                return;
            }
            int position = mBinder.getCurrentPosition();
            int duration = mBinder.getDuration();
            if (position >= 0) {
                mProgress.setMax(duration);
                mProgress.setProgress(position);
            }
        }
    };
    //*****************************************************

    MusicService.IMusicChangeListener mListener = new MusicService.IMusicChangeListener() {
        @Override
        public void onMusicChange(MusicInfo info) {
            if (info != null) {
                mHandler.sendMessage(mHandler.obtainMessage(0, info));
            }
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mRootView != null) {
                mRootView.setVisibility(View.VISIBLE);
            }
            MusicInfo info = (MusicInfo) msg.obj;
            if (getActivity() == null || getContext() == null || info == null) {
                return;
            }
            Glide.with(getContext()).load(info.getImage()).fitCenter().into(mAlbumArt);
            mTitle.setText(info.getName());
            mPlayPause.setImageResource(mBinder.isPlaying() ? R.drawable.audio_player_pause : R.drawable.audio_player_play);
        }
    };

    private void togglePlay() {
        if (mBinder == null) {
            return;
        }
        boolean isPlaying = mBinder.isPlaying();
        if (!mBinder.isReadyForPlay()) {
            return;
        }
        if (isPlaying) {
            mBinder.pause();
        } else {
            mBinder.resume();
        }
        mPlayPause.setImageResource(isPlaying ? R.drawable.audio_player_play : R.drawable.audio_player_pause);
    }

    public void setMusicList(ArrayList<MusicInfo> list, int index) {
        if (mBinder != null) {
            mBinder.setMusicList(list, index);
        }
    }

    @Override
    public void onServiceBinded(MusicService.PlayerBinder binder) {
        mBinder = binder;
        mBinder.registerMusicChangeListener(mListener);
    }

    @Override
    public void onServiceUnBinded() {
        mBinder = null;
    }
}